//
//  ZYQAddFriendViewController.m
//  小庆聊天室
//
//  Created by 张毓庆 on 13-12-9.
//  Copyright (c) 2013年 张毓庆. All rights reserved.
//

#import "ZYQAddFriendViewController.h"
#import "ZYQAppDelegate.h"
#import "NSString+Helper.h"
#import "ZYQLoginUser.h"

@interface ZYQAddFriendViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *addFrindNameText;

@end

@implementation ZYQAddFriendViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self.addFrindNameText becomeFirstResponder];
}

#pragma mark - textfield的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // 判断文本框中是否输入了内容
    NSString *name = [textField.text trimString];
    
    if (![name isEmptyString])
    {
        [self addFriendWithName:name];
    }
    
    return YES;
}

- (void)addFriendWithName:(NSString *)name
{
    // 判断是否有域名了
    NSRange range = [name rangeOfString:@"@"];
    
    if (NSNotFound == range.location)
    {
        name = [NSString stringWithFormat:@"%@@%@",name,[ZYQLoginUser sharedZYQLoginUser].hostName];
        
    }
    
    // 判断是否与当前用户相同
    if ([name isEqualToString:[ZYQLoginUser sharedZYQLoginUser].myJIDName])
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"自己不能添加自己!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        return;
    }
    
    // 4. 判断是否已经是自己的好友
    // 注释：userExistsWithJID方法仅用于检测指定的JID是否是用户的好友，而不是检测是否是合法的JID账户
    if ([[xmppDelegate xmppRosterCoreDataStorage] userExistsWithJID:[XMPPJID jidWithString:name] xmppStream:[xmppDelegate xmppStream]]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该用户已经是好友，无需添加！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
    
    
    
    // 发送好友请求
    [[xmppDelegate xmppRoster] subscribePresenceToUser:[XMPPJID jidWithString:name]];
    
    // 提示用户发送成功
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加好友请求已发送" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [alert show];
}

#pragma mark - alertView的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[self navigationController] popViewControllerAnimated:YES];
}
@end
